package com.service;

import static com.def.GenericDef.E_HPSHTHIS_INVALID_INPUT;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;
import static com.def.GenericDef._NORMAL;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IBisDataDao;
import com.dao.IBisOpeDao;
import com.dao.IHisRetPrdInfoDao;
import com.icim.service.ICIMBaseService;
import com.model.Bis_data;
import com.model.Bis_ope;
import com.model.Bis_opeId;
import com.model.his.His_ret_prd_info;
import com.tx.Hpshthis.HpshthisI;
import com.tx.Hpshthis.HpshthisO;
import com.tx.Hpshthis.HpshthisOA;
import com.util.MqOpe;
import com.util.Util;

@Scope("prototype")
@Service("HpshthisService")
public class HpshthisService extends ICIMBaseService{
	private static Logger logger = Logger.getLogger(XpinqboxService.class);
	private static String TX_NAME = "HPSHTHIS";

	private HpshthisI inTrx;
	private HpshthisO outTrx;

	@Autowired
	private IHisRetPrdInfoDao hisRetPrdInfoDao;
	@Autowired
	private IBisOpeDao bisOpeDao;
	@Autowired
	private IBisDataDao bisDataDao;
	
	@Resource
	private SessionFactory sessionFactoryHis;
	private String gszMsgBuf = "";

	public String subMainProc(String strInMsg) {
		long rtnCode = _NORMAL;
		gszMsgBuf = "";
		String outMsg = "";
		inTrx = new HpshthisI();
		outTrx = new HpshthisO();
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

		MqOpe mqOpe = new MqOpe();

		try {
			inTrx = (HpshthisI) mqOpe.inStr2Obj(strInMsg, inTrx);
			logger.info("InTrx is " + strInMsg);

			rtnCode = subMainProc2(inTrx.getAction_flg().toCharArray()[0]);
			if (rtnCode != _NORMAL) {
				outTrx.setRtn_code(String.valueOf(rtnCode));
				outTrx.setRtn_mesg(gszMsgBuf);
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
			} else {
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				hisRetPrdInfoDao.flushCurSession();
			}
		} catch (Exception ex) {
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logger.error(Util.stackTraceToString(ex));
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
		} finally {
			outMsg = mqOpe.obj2Str(outTrx);
			return outMsg;
		}
	}

	private long subMainProc2(char actionType) {
		long rtnCode = _NORMAL;

		switch (actionType) {
		case 'Q': {
			rtnCode = getShtHistoryInfo();
			break;
		}
		default: {
			gszMsgBuf = "Invalide type input: [" + actionType + "]";
			return E_HPSHTHIS_INVALID_INPUT;
		}
		}
		return rtnCode;
	}

	private long getShtHistoryInfo() {
		long lRc = _NORMAL;
		String prd_seq_id = inTrx.getPrd_seq_id();
		String evt_cate = inTrx.getEvt_cate();
		Session session = sessionFactoryHis.openSession();
		
		String hql = "FROM His_ret_prd_info where prd_seq_id = '"+prd_seq_id+"'";
		if (!Util.isSpaceCheck(evt_cate)) {
			hql += "and evt_cate = '" + evt_cate + "' ";
		}

		hql += "ORDER BY sta_time_d DESC";
		
		Query query = session.createQuery(hql);
		
		List<His_ret_prd_info> his_ret_prd_infoList  =  query.list();
		
//		List<His_ret_prd_info> his_ret_prd_infoList = hisRetPrdInfoDao.list(hql,prd_seq_id);
		
		List<HpshthisOA> oaryList = new ArrayList<HpshthisOA>();
		
		for(His_ret_prd_info his_ret_prd_info: his_ret_prd_infoList){
			HpshthisOA oary = new HpshthisOA();
			String prd_stat = his_ret_prd_info.getPrd_stat();
			try {
				oary.setSta_time_d(Util.getTimestampByDblTime(his_ret_prd_info.getSta_time_d()));
			} catch (Exception e) {
				logger.error(Util.stackTraceToString(e));
				logger.error("<====== Error occurs when conver double time to timestamp ====>");
				logger.error(e.getMessage());
			}
//			oary.setSta_time_d(Util.getTimestampByDblTime(his_ret_prd_info.getId().getSta_time_d()));
			oary.setEvt_cate(his_ret_prd_info.getEvt_cate());
			oary.setBox_id_fk(his_ret_prd_info.getBox_id_fk());
			oary.setSlot_no(his_ret_prd_info.getSlot_no());
			oary.setMdl_id_fk(his_ret_prd_info.getMdl_id_fk());
			
			oary.setAc_recipe_id(his_ret_prd_info.getAc_recipe_id());
			oary.setDs_recipe_id(his_ret_prd_info.getDs_recipe_id());
			oary.setPrd_qty(his_ret_prd_info.getPrd_qty());
			oary.setTool_port_id_fk(his_ret_prd_info.getTool_port_id_fk());
			
			if(("INPR").equals(prd_stat)||("RMPI").equals(prd_stat)||("RMWI").equals(prd_stat) ){
				oary.setOpe_no_fk(his_ret_prd_info.getCr_ope_no_fk());
				oary.setOpe_id_fk(his_ret_prd_info.getCr_ope_id_fk());
				oary.setOpe_ver_fk(his_ret_prd_info.getCr_ope_ver_fk());
				oary.setToolg_id_fk(his_ret_prd_info.getCr_toolg_id_fk());
//				oary.setTool_id_fk(his_ret_prd_info.getCr_tool_id_fk());
	            oary.setPath_id_fk(his_ret_prd_info.getCr_path_id_fk());
	            oary.setPath_ver_fk(his_ret_prd_info.getCr_path_ver_fk());
	            oary.setProc_id_fk(his_ret_prd_info.getCr_proc_id_fk());
			}else{
				oary.setOpe_no_fk(his_ret_prd_info.getNx_ope_no_fk());
				oary.setOpe_id_fk(his_ret_prd_info.getNx_ope_id_fk());
				oary.setOpe_ver_fk(his_ret_prd_info.getNx_ope_ver_fk());
				oary.setToolg_id_fk(his_ret_prd_info.getNx_toolg_id_fk());
//				oary.setTool_id_fk(his_ret_prd_info.getNx_tool_id_fk());
	            oary.setPath_id_fk(his_ret_prd_info.getNx_path_id_fk());
	            oary.setPath_ver_fk(his_ret_prd_info.getNx_path_ver_fk());
	            oary.setProc_id_fk(his_ret_prd_info.getNx_proc_id_fk());
			}
			//TODO:获取站点信息中文说明
			Bis_opeId opeId = new Bis_opeId();
			opeId.setOpe_id(oary.getOpe_id_fk());
			opeId.setOpe_ver(oary.getOpe_ver_fk());
			Bis_ope bis_ope = bisOpeDao.get(opeId);
			if(bis_ope !=null){
				oary.setOpe_no_dsc(bis_ope.getOpe_dsc());
			}
			
            oary.setDest_shop(his_ret_prd_info.getDest_shop());
			//TODO:获取宣告类型的中文说明.
			String sql ="From Bis_data where data_cate='EVCT'and data_id='"+oary.getEvt_cate()+"'";
			List <Bis_data>bis_data_list = bisDataDao.find(sql);
			if(bis_data_list.size() != 0){
				oary.setEvt_cate_dsc(bis_data_list.get(0).getData_desc());
			}else{
				oary.setEvt_cate_dsc(oary.getEvt_cate());
			}
			String sql_dest ="From Bis_data where data_cate='DEST'and data_id='"+oary.getDest_shop()+"'";
			List <Bis_data> bis_data_list_dest = bisDataDao.find(sql_dest);
			if(bis_data_list_dest.size() != 0){
				oary.setDest_shop_dsc(bis_data_list_dest.get(0).getData_desc());
			}else{
				oary.setDest_shop_dsc(oary.getDest_shop());
			}
			oary.setTool_id_fk(his_ret_prd_info.getCr_tool_id_fk());
            oary.setEvt_usr(his_ret_prd_info.getEvt_usr());
            oary.setSht_ope_msg(his_ret_prd_info.getSht_ope_msg());
            oary.setDs_recipe_id(his_ret_prd_info.getDs_recipe_id());
            oary.setPrty(his_ret_prd_info.getPrty());
            oary.setMdl_cate_fk(his_ret_prd_info.getMdl_cate_fk());
            oary.setMdl_typ_fk(his_ret_prd_info.getMdl_typ_fk());
            oary.setGroup_id(his_ret_prd_info.getGroup_id());
            oary.setPrd_stat(his_ret_prd_info.getPrd_stat());
            oary.setLot_id(his_ret_prd_info.getLot_id());
            oary.setGroup_id(his_ret_prd_info.getGroup_id());
            oary.setWo_id_fk(his_ret_prd_info.getWo_id_fk());
            oary.setPrd_grade(his_ret_prd_info.getPrd_grade());
            oaryList.add(oary);
            //TODO:批次代码如何获取
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		session.close();
		return lRc;
	}

}
